import React, { useState, useEffect } from 'react';
import {
  List, Card, Button, Input, Select, Tag,
  Space, Modal, Form, message, Badge, Avatar, Layout, Tabs, Tooltip, Alert
} from 'antd';
import {
  QuestionCircleOutlined, CheckCircleOutlined,
  LikeOutlined, UserOutlined, FireOutlined, ClockCircleOutlined, MessageOutlined, StarOutlined, TrophyOutlined
} from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { setQuestions, setLoading, setFilters, addQuestion, addAnswer, updateQuestion, updateAnswer, setError } from '../../store/qaSlice';
import { qaApi } from '../../api/qaApi';

const { Option } = Select;
const { TextArea } = Input;
const { Content, Sider } = Layout;
const { TabPane } = Tabs;

const DEFAULT_AVATAR = 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';

const QAList = () => {
  const dispatch = useDispatch();
  const { questions, loading, error } = useSelector(state => state.qa);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [form] = Form.useForm();
  const currentUser = useSelector(state => state.user.currentUser);

  const loadQuestions = async () => {
    try {
      dispatch(setLoading(true));
      dispatch(setError(null));
      const data = await qaApi.getQuestions();
      if (Array.isArray(data) && data.length === 0) {
        return;
      } else {
        dispatch(setQuestions(data));
      }
    } catch (error) {
      console.error('加载问题列表失败:', error);
    } finally {
      dispatch(setLoading(false));
    }
  };

  useEffect(() => {
    loadQuestions();
  }, []);

  const handleAskQuestion = (values) => {
    const newQuestion = {
      id: Date.now(),
      ...values,
      author: {
        name: currentUser.username,
        avatar: currentUser.avatar,
        isTeacher: currentUser.role === 'teacher'
      },
      createTime: new Date().toLocaleString(),
      viewCount: 0,
      likeCount: 0,
      answerCount: 0,
      answers: [],
      isHot: false
    };

    dispatch(addQuestion(newQuestion));
    setIsModalVisible(false);
    form.resetFields();
    message.success('提问成功！');
  };

  const handleAnswer = (questionId, content) => {
    const newAnswer = {
      id: Date.now(),
      content,
      author: {
        name: currentUser.username,
        avatar: currentUser.avatar,
        isTeacher: currentUser.role === 'teacher'
      },
      createTime: new Date().toLocaleString(),
      likeCount: 0,
      isAccepted: false,
      isRewarded: false
    };

    dispatch(addAnswer({ questionId, answer: newAnswer }));
  };

  const handleLike = (questionId, answerId) => {
    if (answerId) {
      dispatch(updateAnswer({
        questionId,
        answerId,
        updates: { likeCount: questions.find(q => q.id === questionId).answers.find(a => a.id === answerId).likeCount + 1 }
      }));
    } else {
      dispatch(updateQuestion({
        questionId,
        updates: { likeCount: questions.find(q => q.id === questionId).likeCount + 1 }
      }));
    }
  };

  const handleAcceptAnswer = (questionId, answerId) => {
    dispatch(updateAnswer({
      questionId,
      answerId,
      updates: { isAccepted: true }
    }));
    message.success('已采纳该回答！');
  };

  const handleRewardAnswer = (questionId, answerId) => {
    dispatch(updateAnswer({
      questionId,
      answerId,
      updates: { isRewarded: true }
    }));
    message.success('已奖励该回答！');
  };

  const QuestionItem = ({ question }) => (
    <Card
      style={{ marginBottom: 16 }}
      actions={[
        <Tooltip title="查看">
          <Space>
            <UserOutlined />
            {question.viewCount}
          </Space>
        </Tooltip>,
        <Tooltip title="点赞">
          <Space onClick={() => handleLike(question.id)}>
            <LikeOutlined />
            {question.likeCount}
          </Space>
        </Tooltip>,
        <Tooltip title="回答">
          <Space>
            <ClockCircleOutlined />
            {question.answerCount}
          </Space>
        </Tooltip>
      ]}
    >
      <Card.Meta
        avatar={
          <Badge dot={question.author.isTeacher}>
            <Avatar
              src={question.author.avatar || DEFAULT_AVATAR}
              onError={(e) => {
                e.target.onerror = null;
                e.target.src = DEFAULT_AVATAR;
              }}
            />
          </Badge>
        }
        title={
          <Space>
            {question.title}
            {question.isHot && <FireOutlined style={{ color: '#ff4d4f' }} />}
          </Space>
        }
        description={
          <Space direction="vertical" size="small">
            <div>{question.content}</div>
            <Space>
              {question.tags.map(tag => (
                <Tag key={tag} color="blue">{tag}</Tag>
              ))}
              <span style={{ color: '#999' }}>
                <ClockCircleOutlined /> {question.createTime}
              </span>
            </Space>
          </Space>
        }
      />

      {question.answers && question.answers.length > 0 && (
        <List
          className="answer-list"
          itemLayout="vertical"
          dataSource={question.answers}
          renderItem={answer => (
            <List.Item
              actions={[
                <Tooltip title="点赞">
                  <Space>
                    <LikeOutlined />
                    {answer.likeCount}
                  </Space>
                </Tooltip>,
                answer.isAccepted && (
                  <Tooltip title="最佳答案">
                    <CheckCircleOutlined style={{ color: '#52c41a' }} />
                  </Tooltip>
                )
              ]}
            >
              <List.Item.Meta
                avatar={
                  <Badge dot={answer.author.isTeacher}>
                    <Avatar src={answer.author.avatar || DEFAULT_AVATAR} />
                  </Badge>
                }
                title={answer.author.name}
                description={answer.createTime}
              />
              {answer.content}
            </List.Item>
          )}
        />
      )}
    </Card>
  );

  return (
    <Layout>
      <Content style={{ padding: '0 24px', minHeight: 280 }}>
        {error && (
          <Alert
            message="加载失败"
            description={error}
            type="error"
            showIcon
            style={{ marginBottom: 16 }}
            action={
              <Button type="primary" onClick={() => loadQuestions()}>
                重新加载
              </Button>
            }
          />
        )}

        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<QuestionCircleOutlined />}
            onClick={() => setIsModalVisible(true)}
          >
            我要提问
          </Button>
        </div>

        <Tabs defaultActiveKey="latest">
          <TabPane
            tab={
              <Space>
                <ClockCircleOutlined />
                最新问题
              </Space>
            }
            key="latest"
          >
            <List
              loading={loading}
              dataSource={questions}
              renderItem={question => (
                <QuestionItem question={question} />
              )}
              locale={{
                emptyText: '暂无问题'
              }}
            />
          </TabPane>
          <TabPane
            tab={
              <Space>
                <FireOutlined />
                热门问题
              </Space>
            }
            key="hot"
          >
            <List
              dataSource={questions.filter(q => q.isHot)}
              renderItem={question => (
                <QuestionItem question={question} />
              )}
              locale={{
                emptyText: '暂无热门问题'
              }}
            />
          </TabPane>
        </Tabs>

        <Modal
          title="提出问题"
          visible={isModalVisible}
          onCancel={() => setIsModalVisible(false)}
          footer={null}
        >
          <Form
            form={form}
            onFinish={values => {
              const newQuestion = {
                id: Date.now(),
                ...values,
                author: {
                  name: currentUser?.username || '匿名用户',
                  avatar: currentUser?.avatar || DEFAULT_AVATAR,
                  isTeacher: currentUser?.role === 'teacher'
                },
                createTime: new Date().toLocaleString(),
                viewCount: 0,
                likeCount: 0,
                answerCount: 0,
                answers: [],
                isHot: false
              };
              dispatch(addQuestion(newQuestion));
              setIsModalVisible(false);
              form.resetFields();
            }}
            layout="vertical"
          >
            <Form.Item
              name="title"
              label="问题标题"
              rules={[{ required: true, message: '请输入问题标题' }]}
            >
              <Input placeholder="请简要描述你的问题" />
            </Form.Item>
            <Form.Item
              name="content"
              label="问题详情"
              rules={[{ required: true, message: '请输入问题详情' }]}
            >
              <TextArea
                rows={4}
                placeholder="请详细描述你的问题，包括遇到的具体情况、尝试过的解决方法等"
              />
            </Form.Item>
            <Form.Item
              name="tags"
              label="问题标签"
              rules={[{ required: true, message: '请选择至少一个标签' }]}
            >
              <Select
                mode="tags"
                placeholder="选择或输入标签"
                style={{ width: '100%' }}
              >
                <Option value="React">React</Option>
                <Option value="Vue">Vue</Option>
                <Option value="Angular">Angular</Option>
                <Option value="前端开发">前端开发</Option>
                <Option value="后端开发">后端开发</Option>
              </Select>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit" block>
                发布问题
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </Content>

      <Sider width={300} style={{ background: '#fff', padding: 24 }}>
        <Card title="问答社区规则">
          <ul style={{ paddingLeft: 20 }}>
            <li>提问前请先搜索是否已有相似问题</li>
            <li>问题描述要清晰、具体</li>
            <li>遵守社区规范，互相尊重</li>
            <li>优质回答将获得奖励</li>
          </ul>
        </Card>
        <Card title="热门标签" style={{ marginTop: 16 }}>
          <Space wrap>
            <Tag color="blue">React</Tag>
            <Tag color="blue">Vue</Tag>
            <Tag color="blue">Angular</Tag>
            <Tag color="blue">前端开发</Tag>
            <Tag color="blue">后端开发</Tag>
          </Space>
        </Card>
      </Sider>
    </Layout>
  );
};

export default QAList; 